//
//  ComposeViewController.swift
//  SinaWeibo
//
//  Created by 小果 on 16/2/19.
//  Copyright © 2016年 小果. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 发布微博的最大长度
private let XGStatusTextMaxLength = 140

/// 撰写微博控制器
class ComposeViewController: UIViewController,UITextViewDelegate {
    //MARK: - 表情键盘
    ///  表情键盘控制器(如果闭包中调用self.函数，同样会做一次copy，注意循环引用的问题)
    private lazy var keyBoardVC: EmoticonViewController = EmoticonViewController { [weak self] (emoticon) -> () in
//        print(emoticon.chs)
        self?.textView.insertEmoticon(emoticon)
    }

    /// 切换表情键盘
    @objc private func switchEmoticonKeyboard() {
        
        // 当inputView == nil 的时候代表使用的是系统键盘
//        printLog(textView.inputView)
        // 注销焦点
        textView.resignFirstResponder()
        // 切换键盘
        textView.inputView = (textView.inputView == nil) ? keyBoardVC.view : nil
        // 重新激活焦点
        textView.becomeFirstResponder()
    }
    
    // MARK: - 控件的动画约束
    // 工具栏的底部约束
    private var toolBarBottomConstraint: NSLayoutConstraint?
    // 文本视图底部约束
    private var textViewBttomConstraint: NSLayoutConstraint?
    // 照片选择视图的高度约束
    private var pictureViewHeithtConstraint: NSLayoutConstraint?
    
    // MARK: - 监听方法
    @objc private func close() {
        // 关闭键盘
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    ///  发送微博
    @objc private func sendStatus() {
        // 1、获取带表情符号的文本字符串
        let sendText = textView.emoticonText
        // 2、判断发送微博的长度
        if sendText.characters.count > XGStatusTextMaxLength {
            SVProgressHUD.showInfoWithStatus("亲,您输入的内容过长", maskType: .Gradient)
            
            return
        }
        // 3、发送微博
        NetworkTools.sharedTools.sendStatus(sendText, image: pictureSelectVC.pictures.last).subscribeNext({ (result) -> Void in
            // 刚刚发送成功的微博数据字典
//            printLog(result)
            }, error: { (error) -> Void in
                printLog(error)
                SVProgressHUD.showInfoWithStatus("宝贝,您的网络不给力啊...")
            }) { () -> Void in
                self.close()
        }
        
        
    }
    
    ///  选择照片
    @objc private func selectPicture() {
        printLog("选择照片")
        
        // 1、删除文本视图和toolBar之间的约束
        view.removeConstraint(textViewBttomConstraint!)
        // 2、设置文本视图和照片视图之间的约束
        textViewBttomConstraint = NSLayoutConstraint(item: textView, attribute: .Bottom, relatedBy: .Equal, toItem: pictureSelectVC.view, attribute: .Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBttomConstraint!)
        
        // 3、设置高度约束
        pictureViewHeithtConstraint?.constant = UIScreen.mainScreen().bounds.size.height * 0.6
        
        // 4、关闭键盘
        textView.resignFirstResponder()
        
        // 5、动画弹出照片选择view
        UIView.animateWithDuration(0.25) {
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - UITextViewDelegate(文本变化)
    func textViewDidChange(textView: UITextView) {
        placeHoldeLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        // 修改文字长度提示
        let len = XGStatusTextMaxLength - textView.emoticonText.characters.count
        lengthTipLabel.text = String(len)
        lengthTipLabel.textColor = len >= 0 ? UIColor.lightGrayColor() : UIColor.redColor()
    }
    
    // MARK: - 视图生命周期函数
    override func viewDidLoad() {
        super.viewDidLoad()
        // 注册监听方法
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    // 注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    // 键盘变化监听方法
    @objc private func keyboardChanged(noti: NSNotification) {
        // 获取动画的曲线数值
        let curve = noti.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
        
        
        let rect = noti.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        // 获取键盘动画的时间
        let duration = noti.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        toolBarBottomConstraint?.constant = -UIScreen.mainScreen().bounds.height + rect.origin.y
        // 开始动画
        UIView.animateWithDuration(duration) {
            // 设置动画的曲线
            UIView.setAnimationCurve(UIViewAnimationCurve.init(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 判断用户如果已经选择了照片，就不在激活键盘,如果 > 0，就说明已经选择了照片
        if pictureViewHeithtConstraint?.constant == 0 {
            // 激活键盘
            textView.becomeFirstResponder()
            
        }
    }
    
    // MARK: - 创建界面
    ///  专门来创建界面的函数
    override func loadView() {
        view = UIView()
        
        // 将自动调整 ScrollView的缩进取消
        automaticallyAdjustsScrollViewInsets = false
        
        view.backgroundColor = UIColor.whiteColor()
        
        prepareNavigation()
        prepareToolBar()
        prepareTextView()
        preparePictureView()
    }
    
    // MARK: - 照片视图
    private func preparePictureView() {
        // 1、添加子控制器
        addChildViewController(pictureSelectVC)
        
        // 2、添加视图
        view.insertSubview(pictureSelectVC.view, belowSubview: toolBar)
        
        // 3、设置布局
        let size = UIScreen.mainScreen().bounds.size
        let w = size.width
        // 让照片视图的高度为屏幕的60%
        let h: CGFloat = 0 //size.height * 0.6
        let consTraint = pictureSelectVC.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: h))
        // 记录照片视图的高度的约束
        pictureViewHeithtConstraint = pictureSelectVC.view.ff_Constraint(consTraint, attribute: .Height)
//     printLog(pictureViewHeithtConstraint)
    }
    
    // MARK: - 设置文本视图
    private func prepareTextView() {
        view.addSubview(textView)
        
//        textView.text = "分享新鲜事..."
        // 设置布局
        textView.translatesAutoresizingMaskIntoConstraints = false
        // topLayoutGuide: 能够自动判断顶部控件(状态栏，NavBar)
        let viewDict: [String : AnyObject] = ["top": topLayoutGuide,"tb": toolBar, "tv": textView]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tv]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[top]-0-[tv]", options: [], metrics: nil, views: viewDict))
        
        // 定义textView和ToolBar之间的约束
        textViewBttomConstraint = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBttomConstraint!)
        
        // 设置占位标签(占位标签之所以添加到textView上，是因为在拖动textView的时候，占位标签能够跟着一起滑动)
        textView.addSubview(placeHoldeLabel)
        placeHoldeLabel.frame = CGRect(origin: CGPoint(x: 5, y: 8), size: placeHoldeLabel.bounds.size)
        
        // 设置长度提示标签
        view.addSubview(lengthTipLabel)
        lengthTipLabel.ff_AlignInner(type: ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -XGStatusCellMargin, y: -XGStatusCellMargin))
    }
    
    // MARK: - 设置工具栏
    private func prepareToolBar() {
        
        view.addSubview(toolBar)
        
        // 设置背景颜色
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        // 设置toolbar的自动布局
        let width = UIScreen.mainScreen().bounds.width
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: width, height: 44))
        // 记录底部约束
        toolBarBottomConstraint = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
//        printLog(toolBarBottomConstraint)
        
        // 定义按钮数组
        let itemSetting = [["imageName": "compose_toolbar_picture","action": "selectPicture"],["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "switchEmoticonKeyboard"],
            ["imageName": "compose_addbutton_background"]]
        // 实例化item数组
        var items = [UIBarButtonItem]()
        for dict in itemSetting {
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["action"]))
            // 每个按钮之间添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
    }
    
    // MARK: - 设置导航栏
    private func prepareNavigation () {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        // 默认的发送按钮是禁用状态
        navigationItem.rightBarButtonItem?.enabled = false
        // 导航栏的标题视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        let titleLabel = UILabel(title: "发微博", color: UIColor.blackColor(), fontSize: 15)
        let nameLabel = UILabel(title: userAccountViewModel.sharedUserAccount.userAccount?.name, color: UIColor.lightGrayColor(), fontSize: 13)
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        // 设置布局
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
    }
    
    // MARK: - 懒加载控件
    // 文本视图
    private lazy var textView: UITextView = {
        
        let tv = UITextView()
        // 设置字体
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        // 允许拖拽
        tv.alwaysBounceVertical = true
        // 当拖拽textView的时候关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        // 设置代理
        tv.delegate = self
        
        return tv
    }()
    
    // MARK: - 占位标签
    private lazy var placeHoldeLabel: UILabel = UILabel(title: "分享新鲜事...", color: UIColor.lightGrayColor(), fontSize: 18)
    // MARK: - 长度提示标签
    private lazy var lengthTipLabel: UILabel = UILabel(title: nil, color: UIColor.lightGrayColor(), fontSize: 12)
    
    // MARK: - 工具栏
    private lazy var toolBar = UIToolbar()
    
    // MARK: - 照片选择控制器
    private lazy var pictureSelectVC = PictureSelectController()
    
}
